// utils/mini-marked.js
// 适合微信小程序的极简markdown转html工具，适配rich-text
function escapeHtml(str) {
  return str.replace(/[&<>"]/g, function (tag) {
    const charsToReplace = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;'
    };
    return charsToReplace[tag] || tag;
  });
}

function md2html(md) {
  if (!md) return '';
  let html = escapeHtml(md);
  // 标题
  html = html.replace(/^###### (.*)$/gm, '<div class="md-h6">$1</div>')
             .replace(/^##### (.*)$/gm, '<div class="md-h5">$1</div>')
             .replace(/^#### (.*)$/gm, '<div class="md-h4">$1</div>')
             .replace(/^### (.*)$/gm, '<div class="md-h3">$1</div>')
             .replace(/^## (.*)$/gm, '<div class="md-h2">$1</div>')
             .replace(/^# (.*)$/gm, '<div class="md-h1">$1</div>');
  // 粗体、斜体
  html = html.replace(/\*\*([^*]+)\*\*/g, '<span class="md-strong">$1</span>')
             .replace(/\*([^*]+)\*/g, '<span class="md-em">$1</span>');
  // 有序列表
  html = html.replace(/^(\d+)\. (.*)$/gm, '<div class="md-ol-item">$1. $2</div>');
  // 无序列表
  html = html.replace(/^[-*] (.*)$/gm, '<div class="md-ul-item">• $1</div>');
  // 换行
  html = html.replace(/\n{2,}/g, '</div><div>');
  html = '<div>' + html + '</div>';
  // 链接
  html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<span class="md-link" data-href="$2">$1</span>');
  return html;
}

module.exports = {
  md2html
}; 